package com.rdk.service.impl;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rdk.dao.TUserGroupMapper;
import com.rdk.dao.TUserGroupMemberMapper;
import com.rdk.entity.TUserGroup;
import com.rdk.entity.TUserGroupMember;
import com.rdk.service.TUserGroupService;
import com.rdk.service.TUserService;
import com.rdk.utils.BusinessException;
import com.rdk.utils.CommonUtil;
import com.rdk.utils.StringUtil;

@Service
public class TUserGroupServiceImpl extends BaseServiceImpl<TUserGroup>  implements TUserGroupService {

	@Autowired
	private TUserGroupMapper mapper;
	
	@Autowired
	private TUserGroupMemberMapper userGroupMemberMapper;
	
	@Autowired
	private TUserService userService;
	
	/**
     * 查询
     * 
     * @param userId
     * @return
     */
    public JSONObject findUserGroup(String userId) {
    	 
        JSONArray jsonArray = JSONArray.fromObject(mapper.findUserGroup(userId));
        JSONArray enable = new JSONArray(), disable = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject group = jsonArray.getJSONObject(i);
            if ("1".equals(group.optString("type"))) {
                enable.add(group);
            } else {
                disable.add(group);
            }
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("enable", enable);
        jsonObject.put("disable", disable);
        return jsonObject;
    }
    
    /**
     * 新增
     * 
     * @param reqBean
     */
    @Transactional
    public void addUserGroup(HttpServletRequest request,String userId) throws BusinessException {
        String groupId = getIntId();
        String groupName = "";
        String users = CommonUtil.getRequest(request, "users");
        if (StringUtil.isEmpty(users)) {
            throw new BusinessException("请选择好友！");
        }
        JSONArray array = JSONArray.fromObject(users);
        List<TUserGroupMember> members = new ArrayList<TUserGroupMember>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            if (i == 0) {
                groupName = json.getString("name");
            } else if (i == 1) {
                groupName += ", " + json.getString("name");
            } else if (i == 2) {
                groupName += "...";
            }
            TUserGroupMember member = new TUserGroupMember();
            member.setGroupId(groupId);
            member.setFriendUserId(json.getString("id"));
            members.add(member);
        }
        String type = "enable".equals(CommonUtil.getRequest(request, "groupType")) ? "1" : "2";
        TUserGroup group = new TUserGroup();
        group.setGroupId(groupId);
        group.setGroupName(groupName);
        group.setUserId(userId);
        group.setUserCount(members.size());
        group.setType(type);
        group.setTime(new Date());

        mapper.insert(group);
        userGroupMemberMapper.insertBatch(members);
    }
    
    /**
     * 查询
     * 
     * @param groupId
     * @param userId
     * @throws BusinessException
     */
    public JSONObject queryUserGroup(String groupId, String userId) throws BusinessException {
        JSONObject jsonObject = new JSONObject();
        if (StringUtil.isEmpty(groupId)) {
            throw new BusinessException("获取主键失败");
        }
        TUserGroup group = mapper.selectByPrimaryKey(groupId);
        if (group.getUserId().equals(userId)) {
            jsonObject.put("groupId", group.getGroupId());
            jsonObject.put("groupName", group.getGroupName());
            jsonObject.put("userCount", group.getUserCount());
            jsonObject.put("groupTye", "1".equals(group.getType()) ? "enable" : "disable");

            JSONArray array = JSONArray.fromObject(userGroupMemberMapper.selectByGroupId(groupId));
            
//            JSONArray array = JSONArray.fromObject(userGroupMemberMapper.selectByPrimaryKey(groupId));
//            JSONArray jsonArray = new JSONArray();
//            for (int i = 0; i < array.size(); i++) {
//                JSONObject json = array.getJSONObject(i);
//                jsonArray.add(userService.findUserById(json.optString("friendUserId")).getUserInfo());
//            }
            jsonObject.put("users", array);
        }

        return jsonObject;
    }
    
    /**
     * 删除
     * 
     * @param groupId
     * @param userId
     * @throws Exception
     */
    @Transactional
    public void removeUserGroup(String groupId, String userId) throws Exception {
        if (StringUtil.isEmpty(groupId)) {
            throw new Exception("获取主键失败");
        }
        TUserGroup group = mapper.selectByPrimaryKey(groupId);
        if (group.getUserId().equals(userId)) {
        	mapper.deleteByPrimaryKey(groupId);
            userGroupMemberMapper.deleteByGroupId(groupId);
        }
    }
    
    /**
     * 修改
     * 
     * @param reqBean
     * @throws Exception
     */
    @Transactional
    public void updateUserGroup(String groupId, HttpServletRequest request,String userId) throws Exception {
        if (StringUtil.isEmpty(groupId)) {
            throw new Exception("获取主键失败");
        }
        TUserGroup group = mapper.selectByPrimaryKey(groupId);
        if (group.getUserId().equals(userId)) {
            String uids = CommonUtil.getRequest(request, "uids");
            if (StringUtil.isEmpty(uids)) {
                throw new BusinessException("请选择好友！");
            }
            List<TUserGroupMember> members = new ArrayList<TUserGroupMember>();
            for (String uid : uids.split(",")) {
                TUserGroupMember member = new TUserGroupMember();
                member.setGroupId(groupId);
                member.setFriendUserId(uid);
                members.add(member);
            }

            group.setGroupName(CommonUtil.getRequest(request, "groupName"));
            group.setUserCount(members.size());
            mapper.updateByPrimaryKey(group);

            userGroupMemberMapper.deleteByGroupId(groupId);
            userGroupMemberMapper.insertBatch(members);
        }
    }
}